<?php
require_once realpath(dirname(__FILE__).'/../../app/init.php');
AIR2_DBManager::init();
$master_profile = AIR2_DBManager::$master;

if ($master_profile['hostname'] != 'localhost') {
    echo "Loading dumpfile only supported on 'localhost', not '"
        .$conn['hostname']."'.  Exiting!\n";
    exit(0);
}
if ($master_profile['driver'] != 'mysql') {
    echo "Loading dumpfile only supported for mysql, not '"
        .$conn['driver']."'.  Exiting!\n";
    exit(0);
}
/**
 * Load the database from a dump file
 */
$dbname = $master_profile['dbname'];
$usr = $master_profile['username'];
$pw = $master_profile['password'];
array_shift($argv);
if (count($argv) > 0) {
    $dbname = $argv[0];
    if (count($argv) > 1) $usr = $argv[1];
    if (count($argv) > 2) $usr = $argv[2];
}

// make sure we're about to do the right thing
echo " > about to reload database '$dbname' on localhost with user '$usr'... \n";
echo " > continue? (y/n/?)\n > ";
$answer = trim(strtolower(fgets(STDIN)));
if ($answer == '?') {
    echo " > enter the name of the database to load: ";
    $dbname = trim(fgets(STDIN));
    echo " > enter the username: ";
    $usr = trim(fgets(STDIN));
    echo " > enter the password: ";
    $pw = trim(fgets(STDIN));
    $answer = 'y';
}
else if ($answer != 'y') {
    exit(0);
}

// look for the db dump file
$dump_file = '/home/pijuser/air2/air2.sql.gz';
$cleanup_scp = false;
if (!file_exists($dump_file)) {
    echo " > unable to find dumpfile at '$dump_file'!\n";
    echo " > scp-ing from pijnatdev... ";
    $res;
    $tmp = array();
    exec("scp pijnatdev:$dump_file .", $tmp, $res);
    if ($res == 0) {
        echo "complete!\n";
        $dump_file = './air2.sql.gz';
        $cleanup_scp = true;
    }
    else {
        echo "ERROR! Unable to get file! Exiting!\n";
        exit(1);
    }
}

// load the dump file into mysql
//gunzip < [backupfile.sql.gz] | mysql -u [uname] -p[pass] [dbname]
//mysqlimport -u [uname] -p[pass] [dbname] [backupfile.sql]
echo " > executing mysqlimport command... ";
$res;
$tmp = array();
exec("gunzip < $dump_file | mysql -u $usr -p$pw $dbname", $tmp, $res);
if ($res == 0) {
    echo "complete!\n";
}
else {
    echo "ERROR! Exiting!\n";
    exit(1);
}



// cleanup the file, if you scp'd it
if ($cleanup_scp) {
    echo " > cleaning up scp'd file... ";
    $res;
    $tmp = array();
    exec("rm $dump_file", $tmp, $res);
    if ($res == 0) {
        echo "done\n";
    }
    else {
        echo "ERROR! unable to cleanup scp file! Exiting!\n";
        exit(1);
    }
}
?>
